/*
 * Copyright 2016 atnoce.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce;

import com.atnoce.cloud.ColudController;
import com.atnoce.core.BackService;
import com.atnoce.core.SecurityController;
import com.atnoce.pojo.PasswordItem;
import com.atnoce.util.Cache;
import com.atnoce.util.CommonUtil;
import com.atnoce.util.InitContext;
import com.atnoce.view.BeforeLoginController;
import com.atnoce.view.IndexLayoutController;
import com.atnoce.view.LockController;
import com.atnoce.view.LoginLayoutController;
import com.atnoce.view.PassGenSettingLayoutController;
import com.atnoce.view.PasswordItemEditController;
import com.atnoce.view.PreferencesLayoutController;
import java.io.IOException;
import java.util.Map;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventDispatchChain;
import javafx.event.EventDispatcher;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.commons.lang.StringUtils;

/**
 * onepass的主类文件，启动文件
 * @author atonce.com
 */
public class Start extends Application {
    private Stage primaryStage;
    private BorderPane rootPanel;
    BooleanProperty ready=new SimpleBooleanProperty(false);
    @Override
    public void start(Stage primaryStage) {
        this.primaryStage=primaryStage;
	this.primaryStage.setTitle(CommonUtil.APP_NAME);
        this.primaryStage.setOnCloseRequest(e->{
           // System.out.println("关闭事件");
            //退出时判断是否需要同步
        });
        
        try {
            InitContext.init();//初始化系统配置
            if(Boolean.valueOf(Cache.proMap.get("fstart"))){
                //如果是第一次启动就进入前置引导
                  BeforeLoginLayout();
            }else{
                //不是第一次启动，进入登录页面
                initLoginLayout(null);
            }
        } catch (IOException ex) {
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("初始化失败！");
            alert.setContentText("找不到配系统配置文件!");
            alert.showAndWait();
            System.exit(0);
        }
        
         primaryStage.addEventFilter(EventType.ROOT, new EventHandler<Event>(){
            @Override
            public void handle(Event event) {
                if(StringUtils.equals("MOUSE_CLICKED", event.getEventType().getName()))
                    BackService.updateClock();
                //System.out.println(event.getEventType());
            }
            
        });
    }
    public void BeforeLoginLayout(){
        try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/BeforeLogin.fxml"));
            rootPanel=(BorderPane)loader.load();
            Scene scene=new Scene(rootPanel);
            primaryStage.setScene(scene);
            primaryStage.show();
            
            BeforeLoginController controller=loader.getController();
            controller.setStart(Start.this);
        } catch (IOException ex) {
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("启动失败");
            alert.setContentText("加载BeforeLogin.fxml文件发生异常!");
            alert.showAndWait();
            System.exit(0);
        }
    }
    /**
     * 初始化root布局
     * @param account
     */
    public void initLoginLayout(String account){
	try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/LoginLayout.fxml"));
            BorderPane loginPanel=loader.load();

            LoginLayoutController controller=loader.getController();
            controller.setStart(this);
            controller.setColudAccount(account);
            controller.setStage(primaryStage);

            Scene scene=new Scene(loginPanel);
            primaryStage.setScene(scene);
            primaryStage.resizableProperty().setValue(Boolean.FALSE);
            primaryStage.show();
            
           /* Alert alert=new Alert(Alert.AlertType.INFORMATION);
            ObservableList<ButtonType> buttonTypes = alert.getButtonTypes();
            ButtonType get = buttonTypes.get(0);
            buttonTypes.remove(get);
            alert.setHeaderText("正在同步密码库");
            alert.setContentText("请不要关闭");
            alert.show();
            
            //这里执行同步
            if(!StringUtils.isBlank(account)){
                try {
                    InitContext.updateProperties("coludaccount", SecurityController.getSecurityInstence().encryptColudAccount(account));
                    InitContext.updateProperties("actioncloud", "true");
                    InitContext.updateProperties("fdb", "false");
                    InitContext.updateProperties("fstart", "false");
                } catch (Exception ex) {
                    alert.getButtonTypes().add(get);
                    alert.close();
                    Alert alert1=new Alert(Alert.AlertType.ERROR);
                    alert1.setTitle("登录出错");
                    alert1.setHeaderText("云账号加密失败");
                    alert1.setContentText("加密云账号时出现问题!"+ex.getMessage());
                    alert1.showAndWait();
                    return;
                }
            }
            if(Boolean.valueOf(Cache.proMap.get("actioncloud"))&&!StringUtils.isBlank(Cache.proMap.get("coludaccount"))){//已经激活云服务
                //与云服务器联系
                ColudController colud=new ColudController();
                Map<String, Object> sync = colud.sync();
                // DbUtils.openAll();
                if((boolean)sync.get("flag")){
                    alert.setContentText("同步完成");
                    alert.getButtonTypes().add(get);
                    alert.close();
                }else{
                    //同步发生问题
                    Alert alert2=new Alert(Alert.AlertType.WARNING);
                    alert2.setTitle("警告");
                    alert2.setHeaderText("当前计算机未与服务器取得联系!"+sync.get("msg"));
                    alert2.setContentText("将使用离线模式进入");
                    alert2.showAndWait();
                    alert.getButtonTypes().add(get);
                    alert.close();
                }
             }else{
                alert.getButtonTypes().add(get);
                alert.close();
            }*/
	}catch(IOException e){
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("启动失败");
            alert.setContentText("加载LoginLayout.fxml文件发生异常!");
            alert.showAndWait();
            System.exit(0);
	}
    }
    public void initMainLayout(){
	initIndexLayout();
    }
    public void initIndexLayout(){
	try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/IndexLayout.fxml"));
            rootPanel=loader.load();

            Scene scene=new Scene(rootPanel);
            primaryStage.setScene(scene);
            primaryStage.resizableProperty().setValue(Boolean.TRUE);
            IndexLayoutController controller=loader.getController();
            controller.setStart(Start.this);
	}catch(IOException e){
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("启动失败");
            alert.setContentText("加载IndexLayout.fxml文件发生异常!");
            alert.showAndWait();
            System.exit(0);
        }
    }
    public boolean showPassEditDialog(PasswordItem passwordItem){
	try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/PasswordItemEdit.fxml"));
            AnchorPane page=loader.load();

            Stage dialogStage=new Stage();
            dialogStage.setTitle("编辑密码");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            dialogStage.initOwner(primaryStage);
            //dialogStage.initStyle(StageStyle.UNDECORATED);
            Scene scene=new Scene(page);
            dialogStage.setScene(scene);

            PasswordItemEditController controller=loader.getController();
            controller.setStart(Start.this);
            controller.setDialogStage(dialogStage);
            controller.setPdi(passwordItem);

            dialogStage.showAndWait();
            return controller.isOkClicked();
	}catch(IOException e){
           Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("布局文件加载失败");
            alert.setContentText("加载PasswordItemEdit.fxml文件发生异常!");
            alert.showAndWait();
            return false;
	}
    }
    
    public void showPreferencesDialog(){
        try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/PreferencesLayout.fxml"));
            BorderPane bp=loader.load();

            Stage stage=new Stage();
            stage.setTitle("系统设置");
            stage.initModality(Modality.WINDOW_MODAL);
            stage.initOwner(primaryStage);
            Scene scene=new Scene(bp);
            stage.setScene(scene);

            PreferencesLayoutController controller=loader.getController();
            controller.setStart(Start.this);
            controller.setPreferencesDialogStage(stage);

            stage.showAndWait();
	}catch(IOException e){
            e.printStackTrace();
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("布局文件加载失败");
            alert.setContentText("加载PreferencesLayout.fxml文件发生异常!");
            alert.show();
	}
    }
    public void showPwdGenSettingDialog(){
	try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/PassGenSettingLayout.fxml"));
            BorderPane panel=loader.load();

            Stage stage=new Stage();
            stage.setTitle("密码生成器配置");
            stage.initModality(Modality.WINDOW_MODAL);
            stage.initOwner(primaryStage);
            Scene scene=new Scene(panel);
            stage.setScene(scene);

            PassGenSettingLayoutController controller=loader.getController();
            controller.setStart(Start.this);
            controller.setPwdStage(stage);
            stage.showAndWait();
	}catch(IOException e){
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("布局文件加载失败");
            alert.setContentText("加载PassGenSettingLayout.fxml文件发生异常!");
            alert.show();
	}
    }
    public void lock(){
        try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(Start.class.getResource("view/Lock.fxml"));
            rootPanel=loader.load();

            Scene scene=new Scene(rootPanel);
            scene.getStylesheets().add(Start.class.getResource("view/lock.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.resizableProperty().setValue(Boolean.FALSE);
            
            LockController controller=loader.getController();
            controller.setStart(Start.this);
            
        } catch (IOException ex) {
            Alert alert=new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("布局文件加载失败");
            alert.setContentText("加载锁定界面发生异常!");
            alert.show();
        }
    }
    public Stage getPrimaryStage(){
	return primaryStage;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}
